package com.kqzz.common.exception;

import java.lang.reflect.UndeclaredThrowableException;

//import javax.validation.ConstraintViolation;
//import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;

import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.kqzz.common.api.response.Response;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description 自定义全局异常处理
 * @ClassName GlobalControllerExceptionHandler.java
 * @Package com.kqzz.epidemic.common.exception 
 * @author lipeng
 * @date 2019年8月19日 上午9:44:46
 * 
 * @update_Desc
 * @update_Author
 * @update_Date
 */
@Slf4j
@RestControllerAdvice
public class GlobalControllerExceptionAdvice {
	/**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Response handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数", e);
        return new Response().failure("required_parameter_is_not_present||缺少请求参数");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败", e);
        return new Response().failure("could_not_read_json||参数解析失败");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return new Response().failure(message);
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Response handleBindException(BindException e) {
        log.error("参数绑定失败", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        return new Response().failure(message);
    }

    /**
     * 400 - Bad Request
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    @ExceptionHandler(ConstraintViolationException.class)
//    public Response handleServiceException(ConstraintViolationException e) {
//        log.error("参数验证失败", e);
//        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
//        ConstraintViolation<?> violation = violations.iterator().next();
//        String message = violation.getMessage();
//        return new Response().failure("parameter:" + message);
//    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public Response handleValidationException(ValidationException e) {
        log.error("参数验证失败", e);
        return new Response().failure("validation_exception||参数验证失败");
    }

    /**
     * 401 - Unauthorized
     */
//    @ResponseStatus(HttpStatus.UNAUTHORIZED)
//    @ExceptionHandler(BusinessException.class)
//    public Response handleTokenException(BusinessException e) {
//    	if(e.getErrorCode().equals("1000")){
//    		log.error("重复提交", e);
//            return new Response().failure("RepeatSubmit||重复提交");
//    	}else{
//    		log.error("令牌验证失败", e);
//            return new Response().failure("token_exception||令牌验证失败");
//    	}
//    }

    /**
     * 401 - Unauthorized
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NullPointerException.class)
    public Response handleRepeatLoginException(NullPointerException e) {
        log.error("不合法的请求", e);
        return new Response().failure("null_exception||不合法的请求");
    }
    
    /**
     * 404 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Response handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("不存在的请求地址", e);
        return new Response().failure("no_handler_found||不存在的请求地址");
    }
    
    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法", e);
        return new Response().failure("request_method_not_supported||不支持当前请求方法");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Response handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.error("不支持当前媒体类型", e);
        return new Response().failure("content_type_not_supported||不支持当前媒体类型");
    }
    
    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
    	log.error("服务运行异常", e);
        return new Response().failure("exception||"+e.getMessage());
    }
    
    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Response handleException(BusinessException e) {
    	log.error("服务运行异常", e);
        return new Response().failure("exception||"+e.getMessage());
    }
    
    /**
     * 500 - Internal Server Error
     */
    /*@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Response handlerMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
    	log.error("上传文件超出大小限制", e);
        return new Response().failure("maxUploadSize_Exception||上传文件超出大小限制");
    }*/
}
